<?php
/**
 * Created by PhpStorm.
 * User: whwyy
 * Date: 2018/4/4 0004
 * Time: 18:44
 */

namespace Validate;


class TypesOfValidator extends BaseValidator
{
	
	
	const JSON = 'json';
	const FLOAT = 'float';
	const ARRAY = 'array';
	const STRING = 'string';
	const INTEGER = 'integer';
	const SERIALIZE = 'serialize';
	
	/** @var array */
	private $types = [
		self::JSON => 'json',
		self::FLOAT => 'float',
		self::ARRAY => 'array',
		self::STRING => 'string',
		self::INTEGER => 'integer',
		self::SERIALIZE => 'serialize',
	];
	
	/** @var string */
	public $method;
	
	
	/**
	 * @return bool
	 */
	public function trigger()
	{
		if (!in_array($this->method, $this->types)) {
			return true;
		}
		
		$param = $this->getParams();
		if (empty($param) || !isset($param[$this->field])) {
			return true;
		}
		
		$value = $param[$this->field];
		
		$method = $this->method . 'Format';
		
		if ($value === '' || $value === null) {
			return $this->addError('This is not an empty data.');
		}
		
		return $this->{$method}($value);
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function jsonFormat($value)
	{
		if (!is_string($value) || is_numeric($value)) {
			return $this->addError('This is not a JSON data format');
		}
		if (is_null(json_decode($value))) {
			return $this->addError('This is not a JSON data format');
		}
		return true;
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function serializeFormat($value)
	{
		if (!is_string($value) || is_numeric($value)) {
			return $this->addError('This is not a serialize data format');
		}
		if (false === unserialize($value)) {
			return $this->addError('This is not a serialize data format');
		}
		return true;
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function arrayFormat($value)
	{
		if (!is_array($value)) {
			return $this->addError('This is not a array data format');
		}
		return true;
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function stringFormat($value)
	{
		$trim = trim($value);
		if ($trim != $value) {
			return $this->addError('This is not a string data format');
		}
		return true;
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function integerFormat($value)
	{
		$trim = trim($value);
		if (!is_numeric($trim)) {
			return $this->addError('This is not a number data format');
		}
		if ($trim != $value || intval($trim) != $value) {
			return $this->addError('This is not a number data format');
		}
		return true;
	}
	
	/**
	 * @param $value
	 * @return bool
	 */
	private function floatFormat($value)
	{
		$trim = trim($value);
		if (floatval($trim) != $value || !is_float($trim)) {
			return $this->addError('This is not a float data format');
		}
		return true;
	}
	
}